{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5b22a4d3-257c-4f39-82e7-dfc6d3fb1a2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.datasets import fetch_openml\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5b0576e2-c9ab-42ef-917c-719f603337ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rcParams['font.sans-serif']=['SimHei','Arial Unicode MS','DejaVu Sans']\n",
    "plt.rcParams['axes.unicode_minus']=False\n",
    "sns.set_style(\"whitegrid\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6c8db33d-b363-4547-ba98-4920e2a4c881",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据集形状：(506, 14)\n"
     ]
    }
   ],
   "source": [
    "boston=fetch_openml(name=\"boston\",version=1,as_frame=True)\n",
    "df=boston.frame\n",
    "print(f\"数据集形状：{df.shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3300d573-b7fd-4f1d-88f4-bcb5fbaef619",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    24.0\n",
      "1    21.6\n",
      "2    34.7\n",
      "3    33.4\n",
      "4    36.2\n",
      "Name: MEDV, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 数据预处理\n",
    "X=df.drop('MEDV',axis=1)\n",
    "# print(X.head())\n",
    "y=df['MEDV']\n",
    "print(y.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e6bd5e2e-2333-4bf9-a4ca-beca83053ea0",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "66e00d61-d4c5-4798-9400-6c79af429be1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 标准化特征\n",
    "scaler=StandardScaler()\n",
    "X_train_scaled=scaler.fit_transform(X_train)\n",
    "X_test_scaled=scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4b344e38-c1ca-4728-ada8-e2bc57ba8b1b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "均方误差（MSE）：24.29\n",
      "均方根误差（RMSE）：4.93\n"
     ]
    }
   ],
   "source": [
    "# 线性回归模型\n",
    "lr_model=LinearRegression()\n",
    "lr_model.fit(X_train_scaled,y_train)\n",
    "\n",
    "# 预测\n",
    "y_pred_lr=lr_model.predict(X_test_scaled)\n",
    "mse_lr=mean_squared_error(y_test,y_pred_lr)\n",
    "rmse_lr=np.sqrt(mse_lr)\n",
    "print(f\"均方误差（MSE）：{mse_lr:.2f}\")\n",
    "print(f\"均方根误差（RMSE）：{rmse_lr:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43017549-d3a5-40ad-a5c2-1d47735cca96",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 预测示例\n",
    "sample_idx=0\n",
    "sample_features=X_test.iloc[sample_idx:sample_idex+1]\n",
    "sample_actual=y_test.iloc[sample_idx]\n",
    "sample_pred_lr=lr_model.predict(scaler.transform(sample_teatures))[0]\n",
    "\n",
    "print(f\"\\n===预测示例（第{sample_idx+1}个测试样本）===\")\n",
    "print(f\"实际房价：${sample_actual*1000:.0f}\")\n",
    "print(f\"线性回归预测：${sample_pred_lr*1000:.0f}\")\n",
    "print(f\"特征值：{sample_features.iloc[0].to_dict()}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
